// 实现这个项目的构建任务

const { src, dest, parallel, series, watch } = require('gulp');

const del = require('del');
// 定一个开发服务器
const browserSync = require('browser-sync');
const bs = browserSync.create();

const loadPlugins = require('gulp-load-plugins');
const plugins = loadPlugins();

const clean = () => del(['dist', 'temp']);

const style = () =>
  src('src/assets/styles/*.scss', {
    base: 'src',
  })
    .pipe(
      plugins.sass({
        outputStyle: 'expanded',
      })
    )
    .pipe(dest('temp'));

const script = () =>
  src('src/assets/scripts/*.js', {
    base: 'src',
  })
    .pipe(
      plugins.babel({
        presets: ['@babel/preset-env'],
      })
    )
    .pipe(dest('temp'));

const page = () =>
  src('src/*.html', {
    base: 'src',
  })
    .pipe(plugins.swig())
    .pipe(dest('temp'));

const image = () =>
  src('src/assets/images/**', {
    base: 'src',
  })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'));

const font = () =>
  src('src/assets/fonts/**', {
    base: 'src',
  })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'));

const extra = () =>
  src('public/**', {
    base: 'public',
  }).pipe(dest('dist'));

const serve = () => {
  watch('src/assets/styles/*.scss', style);
  watch('src/assets/scripts/*.js', script);
  watch('src/*.html', page);

  bs.init({
    notify: false,
    files: 'temp/**', // dist 下面所有文件
    server: {
      baseDir: ['temp', 'src', 'public'], // 提高构建效率
      routes: {
        '/node_modules': 'node_modules',
      },
    },
  });
};

const useref = () =>
  src('temp/*.html', {
    base: 'temp',
  })
    .pipe(
      plugins.useref({
        searchPath: ['temp', '.'],
      })
    )
    //  html js css
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(dest('dist'));

const compile = parallel(style, script, page);

const build = series(clean, parallel(series(compile, useref), image, font, extra));
const develop = series(compile, serve);

module.exports = {
  compile,
  build,
  serve,
  useref,
  develop
};

/** *
 * 1. yarn add gulp
 * 2. 添加gulpfile.js
 * 3. 新建一个style 的任务
 * 4. base:'src'   添加基准目录
 * 5. 安装  gulp-sass
 */
